
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tests;

import entities.tools.Answer;
import entities.tools.FilledForm;
import entities.tools.Form;
import entities.tools.Question;
import entities.users.AdminUser;
import entities.users.CompanyOwner;
import entities.users.FormOwner;
import entities.users.FormSigner;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import util.other.ENUMQuestionTypes;

/**
 *
 * @author Marek
 */
@WebServlet(name = "test1Servlet", urlPatterns = {"/test1"})
public class DBModelTest extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
 

    @PersistenceContext(name = "test", unitName = "JEE-study-warPU")
    private EntityManager em;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            UserTransaction tx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");

            {
                tx.begin();
                System.out.println("Tests start");

                FormOwner formOwner1 = new FormOwner();
                FormOwner formOwner2 = new FormOwner();
                FormSigner formSigner1 = new FormSigner();
                FormSigner formSigner2 = new FormSigner();
                FormSigner formSigner3 = new FormSigner();
                AdminUser adminUser = new AdminUser();
                CompanyOwner companyOwner = new CompanyOwner();

                Question question1 = new Question();
                Question question2 = new Question();
                Question question3 = new Question();
                Question question4 = new Question();
                Question question5 = new Question();

                Form form1 = new Form();
                Form form2 = new Form();

                Answer answer1 = new Answer();
                Answer answer2 = new Answer();
                Answer answer3 = new Answer();
                Answer answer4 = new Answer();
                Answer answer5 = new Answer();
                Answer answer6 = new Answer();
                Answer answer7 = new Answer();
                Answer answer8 = new Answer();

                System.out.println("All needed have been created");
                //TODO: Check if all tables are correct
                //TODO: Check if all IDS are corretly created
                //TODO: Check if all entities are corretly persisted

                System.out.println("TEST TEST TEST:" + form2.getId());
                companyOwner.getFormSigners().add(formSigner1);
                companyOwner.getFormSigners().add(formSigner2);
                companyOwner.getFormSigners().add(formSigner3);
                companyOwner.getFormOwners().add(formOwner1);
                companyOwner.getFormOwners().add(formOwner2);

                formOwner1.setCompanyOwner(companyOwner);

                formOwner2.setCompanyOwner(companyOwner);
                System.out.println("All users have been created, and have been set correctly");

                companyOwner.getForms().add(form1);
                companyOwner.getForms().add(form2);
                formOwner1.getForms().add(form1);
                formOwner2.getForms().add(form2);

                form1.setName("This is form1 name");
                form1.setDescription("This is form1 descriptions");
                em.persist(question1);
                em.persist(question2);
                em.persist(question3);
                
                form1.getQuestions().add(question1);
                form1.getQuestions().add(question2);
                form1.getQuestions().add(question3);
                
                form1.setCompanyOwner(companyOwner);
                form1.setFormOwner(formOwner1);

                form2.setName("This is form2 name");
                form2.setDescription("This is form2 descriptions");
                em.persist(question4);
                em.persist(question5);
                form2.getQuestions().add(question4);
                form2.getQuestions().add(question5);
                form2.setCompanyOwner(companyOwner);
                form2.setFormOwner(formOwner2);

                question1.setQuestion("This is form1 question1 name");
                question1.setDescription("This is form1 quetion1 description");
                question1.setType(ENUMQuestionTypes.TEXT);
                question1.setForm(form1);
                question2.setQuestion("This is form1 question2 name");
                question2.setDescription("This is form1 quetion2 description");
                question2.setType(ENUMQuestionTypes.TEXT);
                question2.setForm(form1);
                question3.setQuestion("This is form1 question3 name");
                question3.setDescription("This is form1 quetion3 description");
                question3.setType(ENUMQuestionTypes.TEXT);
                question3.setForm(form1);
                question4.setQuestion("This is form2 question4 name");
                question4.setDescription("This is form2 quetion4 description");
                question4.setType(ENUMQuestionTypes.TEXT);
                question4.setForm(form2);
                question5.setQuestion("This is form2 question5 name");
                question5.setDescription("This is form2 quetion5 description");
                question5.setType(ENUMQuestionTypes.TEXT);
                question5.setForm(form2);
                System.out.println("Question have been created correctly");

                question1.getChildQuestions().add(question3);
                question3.setParentQuestion(question1);

                System.out.println("Relation parent<->childs beetween questions has been set corretly");

                System.out.println("->Check if model is ready for development the application");

                em.persist(companyOwner);
                em.persist(formSigner1);
                em.persist(formSigner2);
                em.persist(formSigner3);
                em.persist(adminUser);
                em.persist(form1);
                em.persist(form2);

                tx.commit();
                tx.begin();

                formOwner1.getFormSigners().add(formSigner1);
                formOwner1.getFormSigners().add(formSigner2);
                formOwner2.getFormSigners().add(formSigner3);
                em.merge(formOwner1);
                em.merge(formOwner2);
                em.merge(formSigner1);
                em.merge(formSigner2);
                em.merge(formSigner3);
                formSigner1 = em.find(FormSigner.class, formSigner1.getId());
                formSigner2 = em.find(FormSigner.class, formSigner2.getId());
                formSigner3 = em.find(FormSigner.class, formSigner3.getId());

                tx.commit();
                tx.begin();

                form1 = em.find(Form.class, form1.getId());
                formSigner1 = em.find(FormSigner.class, formSigner1.getId());
                FilledForm filledForm1 = new FilledForm();
                filledForm1.setFormSigner(formSigner1);
                filledForm1.setForm(form1);
                List<Question> questions = form1.getQuestions();
                System.out.println("LICZBA REKORDOW"+form1.getQuestions().size());
                for (Question question : questions) {
                    Answer answer = new Answer();
                    answer.setQuestion(question);
                    answer.setFilledForm(filledForm1);
                    String answerString = "Test1,Test2,Test3";
                    answer.setValue(answerString);
                    filledForm1.getAnswers().add(answer);
                }
                em.persist(filledForm1);
                System.out.println("FormSigner 1 sign the form, giving answer to all questions");

                tx.commit();

            }

        } catch (NamingException ex) {
            Logger.getLogger(DBModelTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NotSupportedException ex) {
            Logger.getLogger(DBModelTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SystemException ex) {
            Logger.getLogger(DBModelTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RollbackException ex) {
            Logger.getLogger(DBModelTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (HeuristicMixedException ex) {
            Logger.getLogger(DBModelTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (HeuristicRollbackException ex) {
            Logger.getLogger(DBModelTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(DBModelTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalStateException ex) {
            Logger.getLogger(DBModelTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Test of DB entity model</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Is DB model correct?</h1><br/>");
            out.println("Remember, to clean whole database before running this servlet.<br/>");
            out.println("It seems, that everything is fine.<br/>");
            out.println("Please check database. Look if all entities have been created correctly.<br/>");
            out.println("Look if all relations have been set correctly.<br/>");
            out.println("Acceptance test - Check following records in database:.<br/>");
            out.println("1. One Company owner, has been created.<br/>");
            out.println("2. Two form owners, have been created.<br/>");
            out.println("3. Two form signers, have been created.<br/>");
            out.println("4. Two forms have been created.<br/>");
            out.println("5. First form contains 3 questions.<br/>");
            out.println("6. Second form contains 2 questions.<br/>");
            out.println("7. Third question, of the first form, is a child for the first question, of the first form.<br/>");
            out.println("8. Both form owners, are set as a childs of, the Company owner.<br/>");
            out.println("9. Both form signers, are linked to company owner, using, the many to many relation.<br/>");
            out.println("10. Both forms, are childs of, the Form Owner.<br/>");
            out.println("11. First form is filled once, and that information is registered, in FilledForm entity.<br/>");
            out.println("So check if in the filledform database table exist only one record. Check this record. Is this record correctly linked to the first Form.<br/>");
            out.println("12. That filled form was filled by first form signer.<br/>");
            out.println("13. That filled form is linked with first form.<br/>");
            out.println("14. That filled form has 3 ansfers, containing 3 ansfer elements each. Every ansfer is linked, to one question. Every of this questions, is linked with first form.<br/>");
            out.println("15. For now, the number of questions of form1 is the same, as ansfers of filled form connected with form 1. This rule should be correct for every form filled.<br/>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
